package com.jd.risk.bankorder.util;
import java.net.InetAddress;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.wangyin.commons.util.Logger;
import com.wangyin.commons.util.LoggerFactory;
import com.wangyin.rediscluster.client.R2mClusterClient;

@Service(value="controllerUtil")
public class ControllerUtil {
	
	private static Logger logger = LoggerFactory.getLogger(ControllerUtil.class);
	
	private static final String RISK_REPORT_CONTROL = "CAYMAN_JOB_CONTROLLER_0";
	
	@Autowired
	@Qualifier(value = "cacheClusterClientFive")
	R2mClusterClient cacheClusterClientFive;
	
	private String preIp = "172.23.86.60";
	
	private static String ip = null;

	/**
	 * redis选举机制
	 */
	public boolean check(){
		//多服务器竞选
		logger.info("多机器JOB选举检查");
		boolean result = false;
		try {
			if(ip == null || "".equals(ip)){
				InetAddress addr = InetAddress.getLocalHost();
				ip=addr.getHostAddress().toString();//获得本机IP
			}
			if(ip.equals(preIp)){
				logger.info("该机器为预发机器，不参与业务！！！");
				return false;
			}
			cacheClusterClientFive.getClient().append(RISK_REPORT_CONTROL, ip + ",");
			String ips = cacheClusterClientFive.getClient().get(RISK_REPORT_CONTROL);
			logger.info("当前集群ip列表:" + ips);
			String ipArray[] = ips.split(",");
			logger.info("被选中机器IP为："+ipArray[0]);
			if(ip.equals(ipArray[0])){
				result = true;
			}
		} catch (Exception e) {
			logger.error("redis链接异常！！！默认不执行统计操作", e);
		}finally{
			cacheClusterClientFive.getClient().expire(RISK_REPORT_CONTROL,30);
		}
		logger.info("多机器JOB选举检查结束，结果为："+result);
		return result;
	}
}